/*  
 * cafe-ajax.js
 * @Author :      GUORUI
 * @CreateDate :  2017年8月14日
 * Copyright (c) 2017, NRIET.　
 * 封闭ajax
 */
;define(function(){
	var createHttpReq = function() {
		var xhr = null;
		if (window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			xhr = new XMLHttpRequest();
		}
		return xhr;
	}
	var post = function(url,params,success,error) {
		var xhr = createHttpReq();
		var parameters = "";
		params = params||{};
		$.each(Object.keys(params),function(i,key){
			parameters += key+"=" + params[key] + "&";
		});
		if (parameters.length > 0) {
			parameters = parameters.substring(0, parameters.length -1);
		}
		xhr.open('post', url, true);
		xhr.responseType = 'arraybuffer';
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xhr.onreadystatechange = function(){
			if (xhr.readyState == 4 && xhr.status == 200)
				success(this);
            if(xhr.status == 404 && error)
                error(this);
		}
        xhr.send(parameters);
	}
	var get = function(url,params,success,error) {
		var xhr = createHttpReq();
		var parameters = "";
		params = params||{};
		$.each(Object.keys(params),function(i,key){
			parameters += key+"=" + params[key] + "&";
		});
		if (parameters.length > 0) {
			parameters = "?"+parameters.substring(0, parameters.length -1);
		}
		xhr.open('get', url+parameters, true);
		xhr.responseType = 'arraybuffer';
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xhr.onreadystatechange = function(){
			if (xhr.readyState == 4 && xhr.status == 200)
				success(this);
            if(xhr.status == 404 && error)
                error(this);
		}
        xhr.send();
	}
	CafeJS.ajax = function(options){
		if (options.type) {
			if (options.type.toUpperCase() == 'POST') {
				post(options.url, options.params, options.success, options.error);
			} else {
				get(options.url, options.params, options.success, options.error);
			}
		} else {
			get(options.url, options.params, options.success, options.error);
		}
	}
});